package com.tutucms.service.util;

import com.tutucms.common.util.CharUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @title:
 * @author: wangxudong
 * @date: 2019/4/22 17:48
 * @version: 1.0
 * @modified :
 */
@Slf4j
public class RequestUtil {

    public static String getRequestBodyUtf8String(HttpServletRequest request) throws IOException {
        BufferedReader br;
        br = new BufferedReader(new InputStreamReader(request.getInputStream(), "UTF-8"));
        String line;
        StringBuilder sb = new StringBuilder();

        while ((line = br.readLine()) != null) {
            sb.append(line);
        }

        return sb.toString();
    }

    public static Map<String, String> getRequestParamToMap(HttpServletRequest request) {
        Map<String, String> maps = new HashMap<>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            // 乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"),"utf-8");
            maps.put(name, valueStr);
        }

        return maps;
    }

    public static Map<String, String> getUrlParams(String param, String charSet) {
        Map<String, String> map = new HashMap<>();
        if (CharUtil.isEmpty(param)) {
            return map;
        }
        String[] params = param.split("&");
        for (int i = 0; i < params.length; i++) {
            String[] p = params[i].split("=");
            if (p.length == 2) {
                String value = p[1];
                try {
                    value = URLDecoder.decode(value, charSet);
                } catch (UnsupportedEncodingException e) {
                    log.warn("url 解码失败." + e.getMessage());
                    value = p[1];
                }
                map.put(p[0], value);
            }
        }
        return map;
    }
}
